// pages/creatshop/creatshop.ts
import { FormEvent } from "miniprogram/@types/Event"
import { File } from "miniprogram/miniprogram_npm/@vant/weapp/uploader/utils"
import {tipMixin} from "@mixin/tip";
import { uploadfile } from "@utils/http";
Page({
  mixins:[tipMixin],
  /**
   * 页面的初始数据
   */
  data: {
    currentIndex:0,
    shopTypes:["娱乐","丽人","生活"],
    form:{
      name:"",
      type:"丽人",
      start:"",
      end:"",
      conditions:new Array<string>(),
      location:"",
      picture:new Array<File>(),
    },
    typeindex:0,
    startpicker:false,
    endpicker:false,
    currenttime:new Date().getTime(),
    shopstart:"请选择时间",
    shopend:"请选择时间",
    onaddcondiction:false,
    sellerRequestDtoS:new Array<{name:string,price:string,description:string,picture:File[]}>(1).fill({name:'',price:'',description:'',picture:[]})
  },
  saveFormData({currentTarget:{dataset:{key}},detail:{value}}:FormEvent<{key:string}>){
    this.setData({
      form:{
        ...this.data.form,
        [key]:value
      }
    })
  },
  changetypeindex(e:FormEvent<{item:string}>){
    this.setData({
      form:{
        ...this.data.form,
        type:e.currentTarget.dataset.item
      }
    })
  },
  del(e:FormEvent<null>){
    let index = e.detail.index   //能获取到对应的下标
    let fileList = this.data.form.picture  //这里是前端页面展示的数组
    this.setData({
      form:{
        ...this.data.form,
        picture:[...fileList.slice(0,index),...fileList.slice(index+1)]
      }
    })
  },
  getimage(e:FormEvent<null>){
  var fileList=this.data.form.picture
  var files=e.detail.file
  files.forEach(item => {
    fileList.push(item)
  });
  this.setData({
    form:{
      ...this.data.form,
      picture:fileList
    }
  })
  },
  showaddcondition(){
  this.setData({
    onaddcondiction:true
  })
  },
  addcondition(e:FormEvent<null>){
    this.setData({
      onaddcondiction:false
    })
    if(!e.detail.value.trim())return 
    const conditions=this.data.form.conditions
    conditions.push(e.detail.value)
    this.setData({
      form:{
        ...this.data.form,
        conditions
      },
    })
  },
  subcondition(e:FormEvent<{index:number}>){
  const index=e.currentTarget.dataset.index
  var conditions=this.data.form.conditions
  this.setData({
    form:{
      ...this.data.form,
      conditions:[...conditions.slice(0,index),...conditions.slice(index+1)]
    }
  })
  },
  getgoodsdetail(e:FormEvent<{index:number,key:string}>){
  const {
    index,
    key,
  }=e.currentTarget.dataset
  if(key==="price"){
    if(Number.isNaN(Number.parseFloat(e.detail.value))){
      e.detail.value=""
    }else{
      e.detail.value=Number.parseFloat(e.detail.value).toString()
    }
  }
  const {sellerRequestDtoS}=this.data
  sellerRequestDtoS[index][key]=e.detail.value
  this.setData({
    sellerRequestDtoS:[...sellerRequestDtoS]
  })
  },
  getgoodsimage(e:FormEvent<{index:number}>){
  var index=e.currentTarget.dataset.index
  const {sellerRequestDtoS}=this.data
  var fileList=[...sellerRequestDtoS[index].picture,...e.detail.file]
  sellerRequestDtoS[index].picture=fileList
  this.setData({
    sellerRequestDtoS:[...sellerRequestDtoS]
  })
  },
  delgoodsimage(e:FormEvent<{index:number}>){
  var {index:goodsIndex}=e.currentTarget.dataset 
  const {sellerRequestDtoS}=this.data
  sellerRequestDtoS[goodsIndex].picture.splice(e.detail.index,1)  //这里是前端页面展示的数组
    this.setData({
      sellerRequestDtoS:sellerRequestDtoS.slice()
    })
  },
  addgoods(){
  const goods=this.data.sellerRequestDtoS
  goods.push({name:'',price:'',description:'',picture:[]})
  this.setData({
    sellerRequestDtoS:[...goods]
  })
  },
  delgoods(e:FormEvent<{index:number}>){
    var index=e.currentTarget.dataset.index
    var goods=this.data.sellerRequestDtoS
    this.setData({
      sellerRequestDtoS:[...goods.slice(0,index),...goods.slice(index+1)]
    })
  },
  tip(message:string,type?:string){},
  verify(){
    const {form,sellerRequestDtoS}=this.data
    if(Object.values(form).some(item=>typeof item==="string"&&!item.trim())){
      this.setData({
        currentIndex:0
      })
      this.tip("请填写完整店铺信息")
      return false
    }
    if(!form.picture.length){
      this.tip("请上传店铺图片")
      return false
    }
    if(sellerRequestDtoS.length){
      if(sellerRequestDtoS.some(goods=>{
        return Object.values(goods).some(item=>{
          return typeof item==="string"&&!item.trim()||Array.isArray(item)&&item.length==0
        })
      })){
        this.setData({
          currentIndex:1
        })
        this.tip("请填写完整的商品信息")
        return false
      }
    }

    return true
  },
  submit:function(){
    if(!this.verify())return
    const that=this
    wx.showModal({
      title:"是否确认提交",
      success:async function(res){
        if(res.confirm){
          const {sellerRequestDtoS,form} =that.data
          const {picture}=form
          const files=new Array<File>()
          const shopPicture=picture.map(item=>{
            files.push(item)
            return item.url.split("/").pop()
          })
          const data:any={
            ...form,
            school:"华农",
            zone:"五山",
            files,
            picture:shopPicture,
          }
          sellerRequestDtoS.forEach((item,index)=>{
            const goods={
              ...item,
              picture:item.picture.map(item=>{
                files.push(item)
                return item.url.split("/").pop()
              })
            }
            Object.keys(goods).forEach(key=>{
              data[`sellerRequestDtoS[${index}].${key}`]=goods[key]
            })
          })
          try{
            wx.showLoading({
              title:"加载中"
            })
            await uploadfile("/shop",data,"files")
            that.tip("创建成功","success")
            setTimeout(()=>{
              wx.navigateBack({delta:1})
            },500)
          }catch(e){
            console.log(e)
            that.tip("创建失败","danger")
          }finally{
            wx.hideLoading()
          }
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})